package com.example.musicaiap.ui.components

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlaylistPlay
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.ui.theme.QQGreen
import java.util.concurrent.TimeUnit

/**
 * 底部迷你播放器组件
 * 
 * @param isVisible 控制组件是否可见
 * @param currentSong 当前播放的歌曲
 * @param isPlaying 是否正在播放
 * @param progress 播放进度
 * @param currentPosition 当前播放位置(毫秒)
 * @param duration 歌曲总时长(毫秒)
 * @param onPlayPause 播放/暂停按钮点击回调
 * @param onSkipNext 下一首按钮点击回调
 * @param onSkipPrevious 上一首按钮点击回调
 * @param onSeek 用户拖动进度条回调
 * @param onPlayerClick 点击播放器区域回调，通常用于导航到全屏播放器
 * @param onPlaylistClick 播放列表按钮点击回调，用于显示当前播放列表
 * @param isInPlaylistScreen 是否在播放列表详情页面，用于控制圆角和边距动画
 */
@Composable
fun MiniPlayer(
    isVisible: Boolean,
    currentSong: Song?,
    isPlaying: Boolean,
    progress: Float,
    currentPosition: Long = 0,
    duration: Long = 0,
    onPlayPause: () -> Unit,
    onSkipNext: () -> Unit,
    onSkipPrevious: () -> Unit,
    onSeek: (Float) -> Unit = {},
    onPlayerClick: () -> Unit,
    onPlaylistClick: () -> Unit,
    isInPlaylistScreen: Boolean = false
) {
    // 动画化圆角值 - 在播放列表页面时底部圆角更大
    val bottomCornerRadius by animateDpAsState(
        targetValue = if (isInPlaylistScreen) 10.dp else 0.dp,
        animationSpec = tween(durationMillis = 300),
        label = "cornerRadius"
    )
    
    // 动画化底部padding - 在播放列表页面时底部padding更大以填充导航栏空间
    val bottomPadding by animateDpAsState(
        targetValue = if (isInPlaylistScreen) 16.dp else 8.dp,
        animationSpec = tween(durationMillis = 300),
        label = "bottomPadding"
    )

    // 滑块交互状态
    val interactionSource = remember { MutableInteractionSource() }
    // 是否正在拖动进度条
    var isDragging by remember { mutableStateOf(false) }
    // 拖动时的进度值
    var dragProgress by remember { mutableStateOf(0f) }

    AnimatedVisibility(
        visible = isVisible && currentSong != null,
        enter = fadeIn() + expandVertically(),
        exit = fadeOut() + shrinkVertically()
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth(),
            color = MaterialTheme.colorScheme.surface,
            shadowElevation = 4.dp,
            shape = RoundedCornerShape(
                bottomStart = bottomCornerRadius,
                bottomEnd = bottomCornerRadius
            )
        ) {
            Column {
                // 可交互的播放进度控制
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 8.dp, vertical = 0.dp)
                ) {
                    Slider(
                        value = if (isDragging) dragProgress else progress,
                        onValueChange = { 
                            isDragging = true
                            dragProgress = it
                        },
                        onValueChangeFinished = {
                            onSeek(dragProgress)
                            isDragging = false
                        },
                        colors = SliderDefaults.colors(
                            thumbColor = QQGreen,
                            activeTrackColor = QQGreen,
                            inactiveTrackColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
                        ),
                        interactionSource = interactionSource,
                        modifier = Modifier.height(24.dp)
                    )
                }
                
                // 时间显示
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 0.dp),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = formatDuration(currentPosition),
                        style = MaterialTheme.typography.bodySmall,
                        fontSize = 11.sp,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                    )
                    
                    Text(
                        text = formatDuration(duration),
                        style = MaterialTheme.typography.bodySmall,
                        fontSize = 11.sp,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                    )
                }
                
                // 迷你播放器主体
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable(onClick = onPlayerClick)
                        .padding(
                            start = 16.dp, 
                            end = 16.dp, 
                            top = 2.dp,
                            bottom = bottomPadding
                        ),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 封面图片
                    currentSong?.let { song ->
                        // 检查封面URL是否是有效URL
                        if ((song.coverUrl.startsWith("http") || song.coverUrl.startsWith("content://")) 
                            && song.coverUrl.isNotEmpty() && !song.coverUrl.startsWith("default://")) {
                            // 使用真实封面
                            AsyncImage(
                                model = ImageRequest.Builder(LocalContext.current)
                                    .data(song.coverUrl)
                                    .crossfade(true)
                                    .build(),
                                contentDescription = "专辑封面",
                                contentScale = ContentScale.Crop,
                                modifier = Modifier
                                    .size(48.dp)
                                    .clip(RoundedCornerShape(4.dp))
                            )
                        } else {
                            // 使用默认音乐图标
                            Box(
                                modifier = Modifier
                                    .size(48.dp)
                                    .clip(RoundedCornerShape(4.dp))
                                    .background(MaterialTheme.colorScheme.surfaceVariant),
                                contentAlignment = Alignment.Center
                            ) {
                                Icon(
                                    imageVector = Icons.Filled.MusicNote,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                    
                    Spacer(modifier = Modifier.width(12.dp))
                    
                    // 歌曲信息
                    Column(
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = currentSong?.title ?: "",
                            style = MaterialTheme.typography.bodyMedium,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                        
                        Text(
                            text = currentSong?.artist ?: "",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                    
                    // 播放控制
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(4.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 播放列表按钮
                        Box(
                            modifier = Modifier
                                .size(36.dp)
                                .clip(CircleShape)
                                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f))
                                .clickable(onClick = onPlaylistClick),
                            contentAlignment = Alignment.Center
                        ) {
                            Icon(
                                imageVector = Icons.Default.PlaylistPlay,
                                contentDescription = "播放列表",
                                tint = MaterialTheme.colorScheme.onSurface,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                        
                        Spacer(modifier = Modifier.width(4.dp))
                        
                        // 上一首按钮
                        Box(
                            modifier = Modifier
                                .size(36.dp)
                                .clip(CircleShape)
                                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f))
                                .clickable(onClick = onSkipPrevious),
                            contentAlignment = Alignment.Center
                        ) {
                            Icon(
                                imageVector = Icons.Default.SkipPrevious,
                                contentDescription = "上一首",
                                tint = MaterialTheme.colorScheme.onSurface,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                        
                        Spacer(modifier = Modifier.width(4.dp))
                        
                        // 播放/暂停按钮
                        Box(
                            modifier = Modifier
                                .size(36.dp)
                                .clip(CircleShape)
                                .background(
                                    if (isPlaying) QQGreen.copy(alpha = 0.1f) 
                                    else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f)
                                )
                                .clickable(onClick = onPlayPause),
                            contentAlignment = Alignment.Center
                        ) {
                            Icon(
                                imageVector = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow,
                                contentDescription = if (isPlaying) "暂停" else "播放",
                                tint = if (isPlaying) QQGreen else MaterialTheme.colorScheme.onSurface,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                        
                        Spacer(modifier = Modifier.width(4.dp))
                        
                        // 下一首按钮
                        Box(
                            modifier = Modifier
                                .size(36.dp)
                                .clip(CircleShape)
                                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f))
                                .clickable(onClick = onSkipNext),
                            contentAlignment = Alignment.Center
                        ) {
                            Icon(
                                imageVector = Icons.Default.SkipNext,
                                contentDescription = "下一首",
                                tint = MaterialTheme.colorScheme.onSurface,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}

/**
 * 格式化时长
 */
private fun formatDuration(durationMs: Long): String {
    val minutes = TimeUnit.MILLISECONDS.toMinutes(durationMs)
    val seconds = TimeUnit.MILLISECONDS.toSeconds(durationMs) - TimeUnit.MINUTES.toSeconds(minutes)
    return String.format("%02d:%02d", minutes, seconds)
} 